#include "curlRequest.h"
#include <errno.h>
#include <string.h>
/**
 * 使用crul发送get请求
 */
void sendGetRequest(char* url,size_t (*fn)(char*, size_t, size_t , void*))
{
    //1.初始化一个curl
    CURL *curl = curl_easy_init();
    //2.给curl设置一些对应的选项(目标地址，回调函数，请求参数，发送文件)
    curl_easy_setopt(curl,CURLOPT_URL,"http://47.109.65.208/config.json");
    //3.发送请求参数
    //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"xx=sss&yy=000");
    //4.设置回调函数
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,fn);
    //5.发送请求
    CURLcode code = curl_easy_perform(curl);
    if (code!=CURLE_OK)
    {
        fprintf(stderr,"curl_easy_perform() failed: %s\n",curl_easy_strerror(code));
    }
    //6.清理
    curl_easy_cleanup(curl);
}

/**
 * 使用crul发送Post请求
 */
void sendPostRequest(char* url,char*parmStr,size_t (*fn)(void*, size_t, size_t , void*)){
     //1.初始化一个curl
    CURL *curl = curl_easy_init();
    //2.给curl设置一些对应的选项(目标地址，回调函数，请求参数，发送文件)
    curl_easy_setopt(curl,CURLOPT_URL,url);
    //3.发送请求参数
    curl_easy_setopt(curl,CURLOPT_POSTFIELDS,parmStr);
    //4.设置回调函数
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,fn);
    //5.发送请求
    CURLcode code = curl_easy_perform(curl);
    if (code!=CURLE_OK)
    {
        fprintf(stderr,"curl_easy_perform() failed: %s\n",curl_easy_strerror(code));
    }
    //6.清理
    curl_url_cleanup(curl);
}

int downloadRes(char* url,char* saveLocalPath)
{
    FILE *saveFilePath = fopen(saveLocalPath ,"wb");
    if (!saveFilePath)//如果打开文件失败
    {
        fprintf(stderr,"failed open file :%s\n",strerror(errno));
        return -1;      
    }
    

    CURL * curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl,CURLOPT_URL,url);//设置url
        curl_easy_setopt(curl,CURLOPT_WRITEDATA,saveFilePath);//设置写入数据的目标
        CURLcode code = curl_easy_perform(curl);//执行请求
        if (code!=CURLE_OK)//检查请求结果
        {
            fprintf(stderr,"curl_easy_perform()error %s\n",curl_easy_strerror(code));
            return -1;
        }
        else
        {
            fclose(saveFilePath);  // 确保文件被关闭
            return -1;
        }

        //清除
        curl_easy_cleanup(curl);
        //关闭文件
        fclose(saveFilePath);
    }
    
}
